package com.wondream.myframework.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;

import java.util.concurrent.*;

class Thread1 extends Thread{
    public void run() {
        ThreadUseTest.logger.info("Thread1");
    }
}

class Thread2 implements Runnable {
    public void run() {
        ThreadUseTest.logger.info("Thread2");
    }
}

class Task implements Callable<Integer> {
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}


// 局部匿名内部类要使用局部变量，局部变量必须是final类型
public class ThreadUseTest {

    public static final Log logger = LogFactory.getLog(ThreadUseTest.class);

    @Test
    public void execute() throws ExecutionException, InterruptedException {
        // 第一种：继承Thread类使用线程
        Thread thread1 = new Thread1();
        thread1.start();
        // 第二种：实现Runnable接口使用线程
        Thread thread2 = new Thread(new Thread2());
        thread2.start();
        // 第三种：使用Thread匿名内部类
        Thread thread3 = new Thread(){
            public void run(){
                ThreadUseTest.logger.info("Thread3");
            }
        };
        thread3.start();
        // 第四种：使用Runnable匿名内部类
        Thread thread4 = new Thread(new Runnable() {
            public void run() {
                ThreadUseTest.logger.info("Thread4");
            }
        });
        thread4.start();
        // 第五种：使用Callable和Future
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        executor.submit(futureTask);
        executor.shutdown();
        // 第六种方式，注意这种方式和第五种方式效果是类似的，只不过一个使用的是ExecutorService，一个使用的是Thread
        /*Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        Thread thread = new Thread(futureTask);
        thread.start();*/

        System.out.println("task运行结果"+futureTask.get());
    }
}

